package com.stress.testing.plugin.apache.http.client.v4.interceptor;

import com.stress.testing.common.StressTesting;
import com.stress.testing.common.TraceContext;
import com.stress.testing.common.TraceContextHolder;
import com.stress.testing.common.interceptor.AbstractInterceptor;
import org.apache.http.HttpRequest;

import java.lang.reflect.Method;

public class CloseableHttpClientExecuteInterceptor extends AbstractInterceptor {
    @Override
    public void before(Method method, Object[] args, Object zuper, Object thiz) {
        if (!StressTesting.enable(getAgentConfig(), getPluginConfig())) {
            return;
        }

        if (args == null || args.length == 0) {
            return;
        }

        HttpRequest request = null;
        Object arg = null;
        if (args != null && args.length > 0) {
            arg = args[0];
            if (arg != null && arg instanceof HttpRequest) {
                request = (HttpRequest) arg;
            } else if (args.length >= 2) {
                arg = args[1];
                if (arg != null && arg instanceof HttpRequest) {
                    request = (HttpRequest) arg;
                }
            }
        }

        if (request == null) {
            return;
        }

        TraceContext traceContext = TraceContextHolder.getTraceContext();
        if (traceContext == null) {
            return;
        }

        // 添加链路信息
        for (String name : traceContext.propertyNames()) {
            request.setHeader(name, traceContext.getProperty(name));
        }
    }
}
